package util;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Parallel
{
	static final int iCPU = Runtime.getRuntime().availableProcessors();

	public static <T> void ForEach(Iterable <T> parameters, final LoopBody<T> loopBody) throws InterruptedException
	{
		long start2 = System.nanoTime();
		int runs1 = 1000;
	    ExecutorService executor = Executors.newFixedThreadPool(iCPU);
	    List<Future<?>> futures  = new LinkedList<Future<?>>();
	
	    for (final T param : parameters)
	    {
	        Future<?> future = executor.submit(new Runnable()
	        {
	            public void run() { loopBody.run(param); }
	        });
	
	        futures.add(future);
	    }
	
	    for (Future<?> f : futures)
	    {
	        try   { f.get(); }
	        catch (InterruptedException e) { } 
	        catch (ExecutionException   e) { }         
	    }
	
	    executor.shutdown(); 
	    executor.awaitTermination(1, TimeUnit.SECONDS);
	    long time2 = System.nanoTime() - start2;
	    System.out.printf("Parallel: Each loop took an average of %,d micro-seconds%n", time2 / runs1 / 1000);

	}
}




